package com.mycinema.biz.impl;

import java.math.BigDecimal;
import java.util.Random;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mycinema.biz.ShoppingCartBiz;
import com.mycinema.dao.MovieDao;
import com.mycinema.entity.CartItem;
import com.mycinema.entity.Movie;
import com.mycinema.entity.Shoppingcart;

@Service("shoppingCartBiz")
public class ShoppingCartBizImpl implements ShoppingCartBiz {

	@Autowired
	private MovieDao movieDao;

	public void addCart(Shoppingcart cart, int id) {// 添加
		// TODO Auto-generated method stub
		CartItem item = findById(cart, id);
		if (item == null) {
			Movie movie = movieDao.getById(id);
			if (movie != null) {
				item = new CartItem();
				item.setId(id);
				item.setQuantity(1);
				item.setTitle(movie.getTitle());
				item.setPrice(new BigDecimal(new Random().nextDouble()));
				cart.getItems().add(item);
			}
		} else {
			// 已经购买过,数量+1
			item.setQuantity(item.getQuantity() + 1);
		}
	}

	public void remove(Shoppingcart cart, int id) {// 删除
		// TODO Auto-generated method stub
		CartItem item = findById(cart, id);
		if (item != null) {
			cart.getItems().remove(item);
		}
	}

	public void update(Shoppingcart cart, int id, int quantity) {// 修改
		// TODO Auto-generated method stub
		CartItem item = findById(cart, id);
		if (item != null) {
			item.setQuantity(quantity);
		}
	}

	// 查找商品是否在购物车
	private CartItem findById(Shoppingcart cart, int id) {
		for (CartItem item : cart.getItems()) {
			if (item.getId() == id) {
				return item;
			}
		}
		return null;
	}
}
